<template>
  <div class="app-container">
    <el-form 
      :model="queryParams" 
      ref="queryRef" 
      :inline="true" 
      style="border-bottom: 1px solid #c9c9c9; margin-bottom: 30px;" 
      v-show="showSearch" 
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          :rules="[
            { required: true, message: '请输入计划名称', trigger: 'blur' },
            {  message: '最多输入10个字符', trigger: 'blur' },
            { validator: validateNameUnique, trigger: ['blur', 'change'] }
          ]"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" style="width: 250px;" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button 
          type="primary" 
          icon="Search" 
          style="background-color: #266FE8; color: white;" 
          @click="handleQuery"
        >搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="display: flex; justify-content: flex-end;" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          style="width: 150px; background-color: #266FE8; color: white;"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['le:item:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="itemList" 
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="创建人" align="center" prop="sysUser.nickName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="项目描述" align="center" prop="description" min-width="200">
        <template #default="scope">
          <div class="description-cell" :title="scope.row.description">
              {{ scope.row.description }}
          </div>
      </template>
      </el-table-column>
      <el-table-column 
        label="操作" 
        align="center"  
        fixed="right" 
        width="200"  
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            style="color: red;"  
            @click="handleDelete(scope.row)" 
            v-hasPermi="['system:plan:remove']"
          >删除</el-button>
          <el-button 
            link 
            type="primary"   
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['system:plan:edit']"
          >编辑</el-button>
          <el-button 
            link 
            type="primary" 
            :style=" {color:scope.row.status?'red':''}" 
            @click="changeStatus(scope.row)" 
            v-hasPermi="['system:plan:edit']"
          >{{scope.row.status?'禁用':'启用'}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改护理项目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="itemRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item 
          label="护理项目名称" 
          prop="name"
          :rules="[
            { required: true, message: '请输入名称', trigger: 'blur' },
            { message: '最多输入10个字符', trigger: 'blur' },
            { validator: validateNameUnique, trigger: ['blur', 'change'] }
          ]"
        >
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input type="number"  v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <!-- <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态(0:禁用 1:启用)">
            <el-option
              v-for="dict in status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="护理项目描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Item">
import { ref, reactive, getCurrentInstance } from 'vue';
import { toRefs } from 'vue';
import { listItem, getItem, delItem, addItem, updateItem } from "@/api/le/item"
import { useUserStore } from '@/store/modules/user'

// 获取若依用户信息
const userStore = useUserStore()

const { proxy } = getCurrentInstance()
const { status } = proxy.useDict('status')

const itemList = ref([])
const allItemList = ref([]) // 存储全部项目，用于名称唯一性校验
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
    id: null,
    name: null,
    image: null,
    price: null,
    unit: null,
    sort: null,
    creator: null,
    createTime: null,
    status: null,
    description: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null,
    originalName: undefined // 用于存储原始名称，供编辑时校验唯一性
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null,
  },
  rules: {
    name: [],
    price: [
      { required: true, message: "价格不能为空", trigger: "blur" },
      {  message: "价格不能为负数", trigger: "blur" }
    ],
    unit: [
      { required: true, message: "单位不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询护理项目列表（同步获取分页列表和全部列表） */
function getList() {
  loading.value = true
  // 1. 获取分页列表（页面表格展示用）
  listItem(queryParams.value).then(response => {
    itemList.value = response.rows
    total.value = response.total
  }).finally(() => {
    loading.value = false // 无论成功失败，都关闭loading
  })

  // 2. 获取全部项目（名称唯一性校验用，pageSize设为9999确保覆盖所有数据）
  listItem({ pageNum: 1, pageSize: 9999, status: null })
    .then(response => {
      allItemList.value = response.rows || [] // 防止返回空导致后续报错
    })
    .catch(error => {
      console.error("获取全部护理项目失败：", error);
      allItemList.value = []; // 错误时初始化为空数组，避免校验崩溃
    });
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    image: null,
    price: null,
    unit: null,
    sort: null,
    creator: null,
    createTime: null,
    status: null,
    description: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null,
    originalName: undefined
  }
  proxy.resetForm("itemRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList() // 搜索时重新获取数据，确保allItemList最新
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加护理项目"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getItem(_id).then(response => {
    form.value = {
      ...response.data,
      originalName: response.data.name // 存储原始名称，编辑时排除自身
    }
    open.value = true
    title.value = "修改护理项目"
  })
}

/** 名称唯一性校验函数（容错+空格处理） */
function validateNameUnique(rule, value, callback) {
  const currentValue = value?.trim()
  if (!currentValue) {
    return callback() // 空值由必填规则处理
  }

  // 容错1：allItemList未加载完成，提示稍等
  if (allItemList.value.length === 0) {
    return callback(new Error('正在加载项目数据，请稍等再试'))
  }

  // 容错2：allItemList不是数组，提示刷新
  if (!Array.isArray(allItemList.value)) {
    return callback(new Error('数据加载异常，请刷新页面重试'))
  }

  const isEdit = !!form.value.id && form.value.originalName !== undefined
  // 编辑时名称未修改，直接通过
  if (isEdit && currentValue === form.value.originalName.trim()) {
    return callback()
  }

  // 校验重复（去除项目名称空格，避免“护理1”和“护理1 ”误判）
  const isDuplicate = allItemList.value.some(item => {
    const itemName = item.name?.trim()
    if (isEdit) {
      // 编辑时排除当前项目自身
      return itemName === currentValue && item.id !== form.value.id
    } else {
      // 新增时不允许任何重复
      return itemName === currentValue
    }
  })

  isDuplicate 
    ? callback(new Error('该护理项目名称已存在，请更换')) 
    : callback()
}

/** 提交按钮 */
function submitForm() {
  form.value.creator = userStore.id
  proxy.$refs["itemRef"].validate(valid => {
    if (valid) {
      const request = form.value.id ? updateItem : addItem
      request(form.value).then(() => {
        proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功")
        open.value = false
        getList() // 提交后重新获取数据，确保列表和校验数据最新
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm(`是否确认删除护理项目编号为"${_ids}"的数据项？`).then(() => {
    return delItem(_ids)
  }).then(() => {
    getList() // 删除后刷新数据
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// 禁用启用
function changeStatus(row) {
  const targetStatus = row.status ? 0 : 1
  const confirmMsg = targetStatus === 0 
    ? `是否确认禁用护理项目编号为"${row.id}"的数据项？`
    : `是否确认启用护理项目编号为"${row.id}"的数据项？`

  proxy.$modal.confirm(confirmMsg).then(() => {
    return updateItem({ ...row, status: targetStatus })
  }).then(() => {
    getList() // 状态修改后刷新数据
    proxy.$modal.msgSuccess("状态修改成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('le/item/export', {
    ...queryParams.value
  }, `item_${new Date().getTime()}.xlsx`)
}

// 组件初始化时加载数据
getList()
</script>

<style scoped>
.approval-result {
  max-width: 600px;
}
.approval-status {
  text-align: center;
  padding: 30px 0;
}
.status-icon {
  font-size: 40px;
  color: #909399;
  margin-bottom: 16px;
}
.operation-record {
  margin-top: 20px;
  background-color: #eaebed;
  padding: 30px;
}
.operation-record h5 {
  font-size: 16px;
  margin-bottom: 12px;
}
.showMessage{
    width: 100%;
    margin: 20px 350px;
}
.approval-page {
  display: flex;
  gap: 20px;
  padding: 20px;
}
.left-column, .right-column {
  flex: 1;
}
.info-card, .approval-card, .record-card {
  height: fit-content;
}
.card-header {
  font-size: 16px;
  font-weight: bold;
}
.description-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>